from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator, MaxValueValidator
from core.models.student import Student
from .base_model import BaseModel
from django.utils import timezone


class DisciplineType(BaseModel):
    name = models.CharField('违纪类型', max_length=50, unique=True)
    description = models.TextField('类型描述', blank=True, null=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '违纪类型'
        verbose_name_plural = '违纪类型管理'


class DisciplineRecord(BaseModel):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, verbose_name='学生')
    discipline_type = models.ForeignKey(DisciplineType, on_delete=models.PROTECT, verbose_name='违纪类型')
    happened_at = models.DateTimeField('违纪时间')
    place = models.CharField('违纪地点', max_length=100)
    description = models.TextField('违纪详情')
    punishment = models.TextField('处分措施')
    points_deducted = models.IntegerField('扣分数', validators=[MinValueValidator(0), MaxValueValidator(100)])
    recorder = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='记录人')
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    def __str__(self):
        return f"{self.student.name} - {self.discipline_type.name} - {self.happened_at.strftime('%Y-%m-%d')}"

    class Meta:
        verbose_name = '违纪记录'
        verbose_name_plural = '违纪记录管理'
        ordering = ['-happened_at']


class DisciplineAppeal(BaseModel):
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    APPEAL_STATUS = [
        ('pending', '待处理'),
        ('approved', '已批准'),
        ('rejected', '已驳回'),
    ]

    record = models.OneToOneField(DisciplineRecord, on_delete=models.CASCADE, verbose_name='违纪记录')
    appeal_reason = models.TextField('申诉理由')
    appeal_file = models.FileField('申诉材料', upload_to='discipline_appeals/', blank=True, null=True)
    appeal_date = models.DateTimeField('申诉日期', auto_now_add=True)
    appeal_status = models.CharField('申诉状态', max_length=20, choices=APPEAL_STATUS, default='pending')
    appeal_result = models.TextField('申诉结果', blank=True, null=True)
    handler = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='处理人')
    handled_at = models.DateTimeField('处理时间', blank=True, null=True)

    def __str__(self):
        return f"{self.record.student.name} - 申诉"

    class Meta:
        verbose_name = '违纪申诉'
        verbose_name_plural = '违纪申诉管理'